import React, {PropsWithChildren, useMemo, useState} from 'react'
import {ScrollView, View} from "@tarojs/components";
import {ActionSheet, Button, Checkbox, SearchBar} from "@nutui/nutui-react-taro";

import styles from "./SelectableListActionSheet.module.sass"

export interface SelectableListActionSheetProps extends PropsWithChildren {
    visible: boolean
    onCancel: () => void
    value: (number | string)[]
    onChange: (values: (string)[]) => void
    options: {
        key: number | string
        label: string
    }[]
}


const SelectableListActionSheet: React.FC<SelectableListActionSheetProps> = (props) => {
    const allSelected = useMemo(() => {
        return props.options.every(option => props.value.includes(option.key))
    }, [props.value, props.options])
    const [keyword,setKeyword] = useState("")
    return <>
        <ActionSheet visible={props.visible}
                     onCancel={props.onCancel}>
            <ScrollView style={{height: 500}} scrollY>
                <View className={styles.actionHeader}>
                    <SearchBar placeholder={"搜索"} left={<Checkbox label={"全选"} labelPosition={"right"} checked={allSelected} onChange={value => {
                        if (value) {
                            props.onChange(props.options.map(it => it.key).map(it => it.toString()))
                        } else {
                            props.onChange([])
                        }
                    }}/>} value={keyword} onChange={value => setKeyword(value.trim())} right={<Button size={"small"} onClick={() => {
                        props.onCancel()
                    }} type={"primary"}>确认</Button>}/>
                </View>
                <Checkbox.Group value={props.value?.map(it => it.toString()) ?? []}
                                labelPosition="left" list onChange={props.onChange}>
                    {props.options.filter(it=>!keyword || it.label.includes(keyword)).map(role => {
                        return <Checkbox key={role.key} value={role.key.toString()}>{role.label}</Checkbox>
                    })}
                </Checkbox.Group>
            </ScrollView>
        </ActionSheet>
    </>
}

export default SelectableListActionSheet


